package com.example.demo.optional;

import com.example.demo.model.Author;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.SQLOutput;
import java.util.List;
import java.util.Optional;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-11-23
 * Time: 10:34
 */
public class OptionalDemo {

    public static Optional<Author> getOA() {
        return Optional.ofNullable(Author.getAuthors().get(0));
    }
    public static Optional<Author> getNULL() {
        return Optional.ofNullable(null);
    }

    public static void main4(String[] args) {
        getOA().map(author -> author.getBooks())
                .ifPresent(books -> System.out.println(books));
        getOA().flatMap(author -> Optional.ofNullable(author.getBooks()));

    }

    public static void main3(String[] args) {
        getOA().filter(author -> author.getAge().compareTo(188) > 0)
                .ifPresent(author -> System.out.println(author))
        ;
        boolean present = getOA().filter(author -> author.getAge().compareTo(188) > 0).isPresent();
        System.out.println(present);

    }

    public static void main(String[] args) {
        System.out.println(getOA().get());
//        System.out.println(getNULL().get());
        System.out.println(getNULL().orElse(new Author()));
        System.out.println(getNULL().orElseGet(() -> new Author()));
        System.out.println(getNULL().orElseThrow(() -> new RuntimeException("数据为null")));

    }
    public static void main1(String[] args) {
        List<Author> authors = Author.getAuthors();
        Optional<Author> author1 = Optional.ofNullable(authors.get(0));
        Optional<Author> author2 = Optional.ofNullable(null);
        author1.ifPresent(a -> System.out.println(a));
        author2.ifPresent(a -> System.out.println(a));

        Optional<Author> oa = getOA();
        oa.ifPresent(a -> System.out.println(a));


    }

}
